<script setup lang="ts">
import { reactive, ref } from "vue";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import { useQuery } from "@/hooks/init";
import { useShare } from "@/hooks/share";
import { usePageScroll } from "@/hooks/scroll";
import {
  home_index_api,
  get_guide_certification_audit_api,
} from "@/api/guider_home";
import { data_api } from "@/api/my";
import { EV_LOGIN, EV_ORDER } from "@/constant/event";
import { Account } from "@/utils/account";
import { AppData } from "@/utils/app";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import NavBar from "@/components/nav/bar.vue";
import NavBg from "@/components/nav/bg.vue";
import NavSpace from "@/components/nav/space.vue";
import IndexSearchBar from "./components/index-search-bar.vue";
import Swipe from "@/components/swipe/swipe.vue";
import SwipeDot from "@/components/swipe/dot.vue";
import IndexLiveItem from "./components/index-live-item.vue";
import IndexMenuTitle from "./components/index-menu-title.vue";
import IndexMoreBtn from "./components/index-more-btn.vue";
import IndexNewsItem from "./components/index-news-item.vue";
import IndexInterviewItem from "./components/index-interview-item.vue";
import IndexTabPicker from "./components/index-tab-picker.vue";
import IndexTaskItem from "./components/index-task-item.vue";
import IndexTaskItem2 from "./components/index-task-item2.vue";
import IndexLastStore from "./components/index-last-store.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad((options) => {
  useQuery<{ type?: "guider_share_guider_store"; id?: string }>(
    options as MiniApp.AppLaunchOption,
    (query) => {
      if (query.type === "guider_share_guider_store") {
        Toast.showLoading();
        reloadData()
          .then(() => {
            Toast.hideLoading();
            Router.navigateTo(
              `/package/guider/pages/store/index?id=${query.id}`
            );
          })
          .catch(() => Toast.hideLoading());
      } else {
        reloadData();
      }

      Account.isLogin &&
        get_guide_certification_audit_api().then((resp) => {
          if (resp.status === 0) return;
          popupModal.value?.show(
            {
              content: resp.text,
              showCancel: false,
              confirmText: resp.status === 2 ? "查看消息" : "我知道了",
            },
            () => {
              if (resp.status === 2)
                Router.navigateTo(`/package/guider/pages/apply/detail`);
            }
          );
        });

      AppData.initConfig((config) => {
        shareOption.title = config.share_info.title;
      });

      Account.isLogin && reloadMyData();
      uni.$on(EV_LOGIN, evLoginCallback);
      uni.$on(EV_ORDER, evOrderCallback);
    }
  );
});
onPullDownRefresh(() => {
  reloadData()
    .then(() => uni.stopPullDownRefresh())
    .catch(() => uni.stopPullDownRefresh());
});
const { pageIsScroll, onPageScroll } = usePageScroll();

const reloadData = () => {
  return home_index_api().then((resp) => {
    adList.value = resp.banner;
    menuList.value = resp.icon;
    certificateData.count = resp.auth_guider.count;
    certificateData.text_arr = resp.auth_guider.text_arr;
    certificateData.avatar_url_arr = resp.auth_guider.avatar_url_arr;
    liveList.value = resp.live;

    const industry_news = resp.menu_title.find(
      (i) => i.key === "industry_news"
    );
    if (industry_news) {
      newsData.title = industry_news.show_title;
    }
    newsList.value = resp.industry_news;

    const guider_interview = resp.menu_title.find(
      (i) => i.key === "guider_interview"
    );
    if (guider_interview) {
      interviewData.title = guider_interview.show_title;
      interviewData.desc = guider_interview.sub_title;
    }
    interviewList.value = resp.guider_interview;

    const task = resp.menu_title.find((i) => i.key === "task");
    if (task) {
      taskData.title = task.show_title;
    }
    tempData.taskList = [
      { left: resp.task, right: resp.task_right },
      { left: resp.user_task, right: resp.user_task_right },
    ];
    tabClick(0);
  });
};

const searchClick = () => {
  Router.navigateTo("/pages/search/search");
  // uni.openEmbeddedMiniProgram({
  //   appId: "wx5006d4146a577ab1",
  //   path: `/pages/activity/xt?utm_tid=6670&scenic_id=1930`,
  //   envVersion: "trial",
  // });
};

const adIndex = ref(0);
const adList = ref<any[]>([]);
const adClick = () => {
  const ad = adList.value[adIndex.value];
  ad.url.startsWith("http")
    ? Router.navigateToWeb(ad.url, "1")
    : Router.navigateTo(ad.url);
};

const menuList = ref<any[]>([]);
const menuClick = (index: number) => {
  const menu = menuList.value[index];

  const fn = (isLogin: boolean) => {
    const fn = (isLogin: boolean) => {
      if (menu.link_type === 2) {
        Router.navigateBack();
        Router.navigateToMiniProgram(menu.mini_program_appid, menu.link);
      } else {
        Router.navigateToOrRedirectTo(isLogin, menu.link);
      }
    };

    // 需要认证
    menu.enter_type === 1 ? checkCertificate(fn) : fn(isLogin);
  };

  // 需要登录
  menu.has_login === 1 ? Account.checkLogin(fn) : fn(false);
};

const certificateData = reactive({
  count: "",
  text_arr: [] as string[],
  avatar_url_arr: [] as string[],
});
const certificateClick = () => {
  Router.navigateTo(`/package/guider/pages/certificate/index`);
};

const liveIndex = ref(0);
const liveList = ref<any[]>([]);
const liveClick = () => {
  const live = liveList.value[liveIndex.value];
  if (live.type === 3) {
    const fn = (isLogin: boolean) => {
      // 已购买
      if (myDataLiveList.value.includes(live.id))
        return Router.navigateToOrRedirectTo(isLogin, live.url);

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content: "该课程为付费直播课，需要购买后才能观看哦，是否购买该课程？",
          confirmText: "前往购买",
        },
        () => {
          Router.navigateTo(`/package/mall/pages/live/detail?id=${live.id}`);
        }
      );
    };

    Account.isLogin
      ? fn(false)
      : Account.login(() => {
          reloadMyData().then(() => fn(true));
        });
  } else {
    Account.checkLogin((isLogin) => {
      const fn = () => {
        Router.navigateToOrRedirectTo(isLogin, live.url);
      };

      if (live.type !== 4) return fn();

      // 是 VIP
      if (AppData.userData.is_vip_member === 1) return fn();

      isLogin && Router.navigateBack();
      popupModal.value?.show(
        {
          content:
            "该课程为VIP专属直播课，需要开通导游VIP才能观看哦，是否开通？",
          confirmText: "开通导游VIP",
        },
        () => {
          Router.navigateTo("/package/mall/pages/vip/index");
        }
      );
    });
  }
};

const newsData = reactive({ title: "行业资讯" });
const newsList = ref<any[]>([]);
const newsClick = (index: number) => {
  if (index === -1) return Router.navigateTo(`/package/other/pages/news/index`);

  const news = newsList.value[index] as any;
  if (news.type === 2) {
    const query = Router.dataToQuery({
      src: news.video_url,
      poster: news.pic_url,
      title: news.title,
    });
    Router.navigateTo(`/package/other/pages/news/video?${query}`);
  } else {
    Router.navigateTo(
      `/package/other/pages/news/detail?id=${news.id}&title=${news.title}`
    );
  }
};

const interviewData = reactive({ title: "名导访谈", desc: "" });
const interviewIndex = ref(0);
const interviewList = ref<any[]>([]);
const interviewClick = (id: string) => {
  id
    ? Router.navigateTo(`/package/famous-talk/pages/detail/index?id=${id}`)
    : Router.navigateTo(`/package/famous-talk/pages/guider/index`);
};

const taskData = reactive({ title: "需求广场" });
const tabIndex = ref(0);
const tabClick = (index: number) => {
  tabIndex.value = index;
  const task = tempData.taskList[index];
  taskList.value = task.left;
  taskList2.value = task.right;
  taskIndex.value = 0;
};
const taskIndex = ref(0);
const taskList = ref<any[]>([]);
const taskList2 = ref<any[]>([]);
const taskClick = (index: number) => {
  if (index === -1) {
    popupModal.value?.show({
      content: "请前往三毛游APP进行操作",
      showCancel: false,
      confirmText: "我知道了",
    });
  } else {
    checkCertificate((isLogin) => {
      Router.navigateToOrRedirectTo(isLogin, `/package/square/pages/task/list`);
    });
  }
};

const checkCertificate = (callback: (isLogin: boolean) => void) => {
  Account.checkLogin((isLogin) => {
    // 已认证
    if (AppData.userData.is_guide_certification === 1) return callback(isLogin);

    isLogin && Router.navigateBack();
    popupModal.value?.show(
      {
        content:
          "你好！这里是全球导游人的家园，为了能给你提供针对性的专业内容服务，需要对你身份进行基础认证，敬请理解！",
        confirmText: "开始认证",
        translateY: "-55%",
      },
      () => {
        Router.navigateTo(
          AppData.userData.status === -1
            ? "/package/guider/pages/apply/type"
            : "/package/guider/pages/apply/detail"
        );
      }
    );
  });
};

const myDataLiveList = ref<number[]>([]);
const reloadMyData = () => {
  return data_api<{ live_course?: number[] }>({
    includes: "live_course",
  }).then((resp) => {
    myDataLiveList.value = resp.live_course || [];
  });
};
const evLoginCallback = (e: { type: "cancel" }) => {
  console.info(`触发事件：${EV_LOGIN}`, e);
  e.type === "cancel" || reloadMyData();
};
const evOrderCallback = (e: { type: "pay" }) => {
  console.info(`触发事件：${EV_ORDER}`, e);
  e.type === "pay" || reloadMyData();
};

const popupModal = ref<InstanceType<typeof PopupModal>>();
const tempData = { taskList: [] as { left: any[]; right: any[] }[] };

const { onShareAppMessage, onShareTimeline, shareOption } =
  useShare("/pages/index/index");
</script>

<template>
  <NavBar>
    <view class="index-nav">
      <view @click="searchClick">
        <IndexSearchBar />
      </view>
    </view>
  </NavBar>
  <NavBg :retract="pageIsScroll" url="/static/index-bg.png" />
  <NavSpace />

  <view class="index-ad">
    <view class="index-ad-bg"></view>
    <view class="index-ad-swipe" @click="adClick">
      <Swipe v-model="adIndex" :listData="adList" labelKey="img_url" autoplay />
    </view>
    <view class="index-ad-dot">
      <SwipeDot v-model="adIndex" :total="adList.length" />
    </view>
  </view>

  <view class="index-menu">
    <view
      class="index-menu-item"
      v-for="(i, d) of menuList"
      :key="i.id"
      @click="menuClick(d)"
    >
      <image class="index-menu-icon" :src="i.icon" />
      <view class="index-menu-name">{{ i.name }}</view>
    </view>
  </view>

  <view class="index-certificate" @click="certificateClick">
    <image class="index-certificate-horn" src="/static/index-certificate.png" />
    <view class="index-certificate-line"></view>
    <view class="index-certificate-content">
      <view class="index-certificate-name">
        认证导游总数&nbsp;<text class="index-certificate-num">{{
          certificateData.count
        }}</text
        >&nbsp;人
      </view>
      <view class="index-certificate-user">
        <image
          class="index-certificate-avatar"
          v-for="(i, d) of certificateData.avatar_url_arr"
          :style="{ marginLeft: d === 0 ? 0 : '' }"
          :key="d"
          :src="i"
          mode="aspectFill"
        />
      </view>
    </view>
    <swiper class="index-certificate-swipe" autoplay circular vertical>
      <swiper-item v-for="i of certificateData.text_arr" :key="i">
        <view class="index-certificate-text">{{ i }}</view>
      </swiper-item>
    </swiper>
    <image
      class="index-certificate-arrow"
      src="/static/index-certificate2.png"
    />
  </view>

  <view class="index-live" v-if="liveList.length > 0">
    <swiper
      class="index-live-swipe"
      circular
      autoplay
      @change="(e) => (liveIndex = e.detail.current)"
    >
      <swiper-item v-for="i of liveList" :key="i.id">
        <view class="index-live-item" @click="liveClick">
          <IndexLiveItem :info="i" />
        </view>
      </swiper-item>
    </swiper>
    <view class="index-live-dot">
      <SwipeDot
        v-model="liveIndex"
        :total="liveList.length"
        size="12rpx"
        color="#ff7900"
        backgroundColor="rgba(255, 121, 0, 0.2)"
      />
    </view>
  </view>

  <view class="index-news">
    <view class="index-news-head">
      <IndexMenuTitle :title="newsData.title" />
      <view class="index-news-more" @click="newsClick(-1)">
        <IndexMoreBtn />
      </view>
    </view>
    <view class="index-news-wrapper">
      <view
        class="index-news-item"
        :style="{ width: d / 3 === 0 ? '690rpx' : '' }"
        v-for="(i, d) of newsList"
        :key="i.id"
        @click="newsClick(d)"
      >
        <IndexNewsItem :info="i" :isLarge="d / 3 === 0" />
      </view>
    </view>
  </view>

  <view class="index-interview">
    <view class="index-interview-head">
      <IndexMenuTitle :title="interviewData.title" />
      <view class="index-interview-more" @click="interviewClick('')">
        <IndexMoreBtn />
      </view>
    </view>
    <view class="index-interview-desc">{{ interviewData.desc }}</view>
    <swiper
      class="index-interview-swipe"
      circular
      autoplay
      @change="(e) => (interviewIndex = e.detail.current)"
    >
      <swiper-item v-for="i of interviewList" :key="i.id">
        <view class="index-interview-item" @click="interviewClick(i.id)">
          <IndexInterviewItem :info="i" />
        </view>
      </swiper-item>
    </swiper>
    <view class="index-interview-dot">
      <SwipeDot
        v-model="interviewIndex"
        :total="interviewList.length"
        size="12rpx"
        color="#ff7900"
        backgroundColor="rgba(255, 121, 0, 0.2)"
      />
    </view>
  </view>

  <view class="index-task">
    <view class="index-task-head">
      <IndexMenuTitle :title="taskData.title" />
      <view class="index-task-add" @click="taskClick(-1)">+ 发布需求</view>
    </view>
    <IndexTabPicker :modelValue="tabIndex" @update:modelValue="tabClick" />
    <view class="index-task-wrapper" @click="taskClick(-2)">
      <view style="position: relative; flex-shrink: 0">
        <image class="index-task-bg" src="/static/index-task.png" />
        <swiper
          class="index-task-swipe"
          circular
          autoplay
          @change="(e) => (taskIndex = e.detail.current)"
        >
          <swiper-item v-for="(i, d) of taskList" :key="d">
            <IndexTaskItem :info="i" />
          </swiper-item>
        </swiper>
        <view class="index-task-dot">
          <SwipeDot
            v-model="taskIndex"
            :total="taskList.length"
            color="#ff7900"
            backgroundColor="#dddddd"
          />
        </view>
      </view>
      <view style="flex-shrink: 0">
        <view
          class="index-task-menu"
          :style="{ marginTop: d === 0 ? 0 : '' }"
          v-for="(i, d) of taskList2"
          :key="d"
        >
          <IndexTaskItem2 :info="i" />
        </view>
      </view>
    </view>
  </view>

  <image class="index-footer" src="/static/index-footer.png" />

  <IndexLastStore />

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
page {
  padding-top: 20rpx;
  padding-bottom: 40rpx;
}

.index-nav {
  flex-grow: 1;
  min-width: 0;
  padding-left: 30rpx;
  padding-right: 20rpx;
}

.index-ad {
  position: relative;
  margin: 0 40rpx 52rpx;

  .index-ad-bg {
    position: absolute;
    left: 20rpx;
    top: 18rpx;
    right: 20rpx;
    height: 244rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(20rpx);
  }

  .index-ad-swipe {
    position: relative;
    height: 250rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .index-ad-dot {
    position: absolute;
    right: 30rpx;
    bottom: 20rpx;
  }
}

.index-menu {
  display: flex;
  flex-wrap: wrap;
  padding: 0 16rpx;

  .index-menu-item {
    width: 25%;
    padding-bottom: 26rpx;
  }

  .index-menu-icon {
    display: block;
    width: 100rpx;
    height: 100rpx;
    margin: 0 auto 6rpx;
  }

  .index-menu-name {
    font-size: 24rpx;
    color: #666666;
    line-height: 32rpx;
    text-align: center;
  }
}

.index-certificate {
  position: relative;
  padding: 14rpx 160rpx 12rpx 104rpx;
  margin: 0 30rpx 40rpx;
  border-radius: 20rpx;
  background-color: #ffffff;

  .index-certificate-horn {
    position: absolute;
    left: 18rpx;
    top: 22rpx;
    width: 56rpx;
    height: 56rpx;
  }

  .index-certificate-line {
    position: absolute;
    left: 80rpx;
    top: 14rpx;
    height: 74rpx;
    border-left: 2rpx solid #f3f3f3;
  }

  .index-certificate-content {
    display: flex;
    align-items: center;
  }

  .index-certificate-name {
    min-width: 0;
    font-size: 28rpx;
    color: #242424;
    line-height: 40rpx;
  }

  .index-certificate-num {
    color: #1bc76f;
    font-weight: bold;
  }

  .index-certificate-user {
    display: flex;
    align-items: center;
    flex-shrink: 0;
  }

  .index-certificate-avatar {
    position: relative;
    width: 28rpx;
    height: 28rpx;
    margin-left: -12rpx;
    border-radius: 50%;
    border: 2rpx solid #dddddd;
  }

  .index-certificate-swipe {
    height: 36rpx;
  }

  .index-certificate-text {
    font-size: 24rpx;
    color: #8a968d;
    line-height: 36rpx;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .index-certificate-arrow {
    position: absolute;
    top: 0;
    right: 0;
    width: 166rpx;
    height: 102rpx;
  }
}

.index-live {
  position: relative;
  padding-bottom: 32rpx;
  margin-bottom: 70rpx;

  .index-live-swipe {
    height: 212rpx;
    margin: 0 30rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .index-live-dot {
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
  }
}

.index-news {
  .index-news-head {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 40rpx;
  }

  .index-news-more {
    margin-left: auto;
  }

  .index-news-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding-left: 30rpx;
    padding-bottom: 20rpx;
  }

  .index-news-item {
    width: 336rpx;
    margin-right: 18rpx;
    margin-bottom: 20rpx;
  }
}

.index-interview {
  position: relative;
  padding-bottom: 32rpx;
  margin-bottom: 70rpx;

  .index-interview-head {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 12rpx;
  }

  .index-interview-more {
    margin-left: auto;
  }

  .index-interview-desc {
    padding-left: 30rpx;
    margin-bottom: 30rpx;
    font-size: 26rpx;
    color: #999999;
    line-height: 36rpx;
  }

  .index-interview-swipe {
    height: 348rpx;
    margin: 0 30rpx;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .index-interview-dot {
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
  }
}

.index-task {
  margin-bottom: 70rpx;

  .index-task-head {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 40rpx;
  }

  .index-task-add {
    padding: 0 18rpx;
    margin-left: auto;
    font-size: 24rpx;
    color: #ff7900;
    line-height: 48rpx;
    font-weight: bold;
    border-radius: 28rpx;
    border: 2rpx solid #ff7900;
  }

  .index-task-wrapper {
    display: flex;
    align-items: center;
    padding-left: 10rpx;
    padding-top: 10rpx;
    background-color: #ffffff;
  }

  .index-task-bg {
    display: block;
    width: 386rpx;
    height: 560rpx;
  }

  .index-task-swipe {
    position: absolute;
    left: 20rpx;
    top: 90rpx;
    width: 346rpx;
    height: 430rpx;
  }

  .index-task-dot {
    position: absolute;
    right: 50rpx;
    bottom: 50rpx;
  }

  .index-task-menu {
    margin-top: 20rpx;
  }
}

.index-footer {
  display: block;
  width: 692rpx;
  height: 70rpx;
  margin: 0 auto;
}
</style>
